using System;
using System.Web.UI.WebControls;

using IBatisNetDemo.Domain;
using IBatisNetDemo.Service;
namespace Web
{
    public partial class _Default : System.Web.UI.Page
    {
        PersonService _personService;
        protected void Page_Load(object sender, EventArgs e)
        {
            //_personService = new IBatisNetDemo.Service.PersonService();
            _personService = Helpers.Person();
            List_Init();
            if (!IsPostBack)
            {
                List_Load();
            }
        }

        private void List_Init()
        {
            btnAdd.Text = "Add New Person";
            //this.btnAdd.Click += new EventHandler(List_Add);
        }
        private void List_Load()
        {
            dgList.DataSource = _personService.GetAllPerson();
            dgList.DataBind();
        }
        protected void List_Delete(object source, DataGridCommandEventArgs e)
        {
            int id = GetKey(dgList, e);
           
            Person _person = new Person();
            _person = _personService.GetPerson(id);
            _personService.Delete(_person);
            List_Load();
        }
        protected void List_Edit(object source, DataGridCommandEventArgs e)
        {
            dgList.EditItemIndex = e.Item.ItemIndex;
            List_Load();
        }
        protected void List_Update(object source, DataGridCommandEventArgs e)
        {
            Person person = new Person();
            person.Id = GetKey(dgList, e);
            person.FirstName = GetText(e, 0);
            person.LastName = GetText(e, 1);
            person.HeightInMeters = GetDouble(e, 2);
            person.WeightInKilograms = GetDouble(e, 3);

            _personService.Update(person);
            List_Load();
        }
        protected void List_Cancel(object source, DataGridCommandEventArgs e)
        {
            dgList.EditItemIndex = -1;
            List_Load();
        }
        private int GetKey(DataGrid dg, DataGridCommandEventArgs e)
        {
            return (Int32)dg.DataKeys[e.Item.DataSetIndex];
        }
        private string GetText(DataGridCommandEventArgs e, int v)
        {
            return ((TextBox)e.Item.Cells[v].Controls[0]).Text;
        }
        private double GetDouble(DataGridCommandEventArgs e, int v)
        {
            return Convert.ToDouble(GetText(e, v));
        }

    }
}
